package com.pangus.toolkits.files.http;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.pangus.toolkits.files.errors.check.HttpException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;

import java.io.IOException;
import java.util.List;

/**
 * @author yingheng chen
 * @description
 * @date 2019/12/3
 */
public class NetworkClient {
    private final OkHttpClient client;

    public NetworkClient(OkHttpClient client) {
        this.client = client;
    }

    public <T> Response<T> call(Request request, Class<T> resultClass) throws IOException {
        okhttp3.Response response = client.newCall(request).execute();
        try (ResponseBody body = response.body()) {
            if (!response.isSuccessful()) {
                throw new HttpException(response.code(), response.body().string());
            }
            String str = body.string();
            JSONObject jsonObject = JSONObject.parseObject(str);
            final Boolean isSuccess = jsonObject.getBoolean("isSuccess");
            if (!isSuccess) {
                throw new HttpException(jsonObject.getInteger("code"), jsonObject.getString("msg"));
            }
            final T result = jsonObject.getObject("data", resultClass);
            return Response.success(result, response, jsonObject);
        } catch (Exception e) {
            throw new HttpException(response.code(), e.getMessage(), e);
        }
    }

    public <T> Response<List<T>> callList(Request request, Class<T> resultClass) throws IOException {
        okhttp3.Response response = client.newCall(request).execute();
        try (ResponseBody body = response.body()) {
            if (!response.isSuccessful()) {
                throw new HttpException(response.code(), response.body().string());
            }
            String str = body.string();
            JSONObject jsonObject = JSONObject.parseObject(str);
            final Boolean isSuccess = jsonObject.getBoolean("isSuccess");
            if (!isSuccess) {
                throw new HttpException(jsonObject.getInteger("code"), jsonObject.getString("msg"));
            }
            JSONArray data = jsonObject.getJSONArray("data");
            List<T> result = data.toJavaList(resultClass);
            return Response.success(result, response, jsonObject);
        } catch (Exception e) {
            throw new HttpException(response.code(), e.getMessage(), e);
        }
    }

    /**
     * @param request okhttp request
     * @return ResponseBody 注意需要手动关闭,否则资源泄露
     * @throws IOException
     */
    public Response<ResponseBody> call(Request request) throws IOException {
        okhttp3.Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new HttpException(response.code(), response.body().string());
        }
        return Response.success(response.body(), response, null);
    }
}
